import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse

def dingding_weather():
    reporttime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    url = "https://restapi.amap.com/v3/weather/weatherInfo"
    key = '高得API'
    data = {'key': key, "city": 城市代码}
    ajson = requests.post(url, data)
    info = dict(ajson.json())
    info = dict(info)
    newinfo = info['lives'][0]
    reporttime = newinfo['reporttime']  # 当前日期和时间
    city = newinfo['province'] + newinfo['city']  # 城市
    weather = newinfo['weather']  # 天气
    temperature = newinfo['temperature'] + '℃'  # 温度
    winddirection = newinfo['winddirection']  # 风向
    windpower = newinfo['windpower'] + "级"  # 风力
    humidity = newinfo['humidity'] + "%"  # 湿度
    aggregate = ("现在是:" + reporttime + "\n当前城市:" + city + "\n今天天气:" + weather + "\n温度:" +
                 temperature + "\n风向:" + winddirection + "\n风力:" + windpower + "\n湿度:" + humidity)
    #以下是钉钉加签
    timestamp = str(round(time.time() * 1000))
    secret = '钉钉机器人加签'#钉钉加签
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    #合并URL并发送出
    url = 'https://oapi.dingtalk.com/robot/send?access_token=钉钉token&timestamp=' + timestamp + '&sign=' + sign
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    data = {
        "msgtype": "text",
        "text": {
            "content": aggregate
        },
    }
    res = requests.post(url, data=json.dumps(data), headers=headers)
    print(res.text)

dingding_weather()